package com.itheima.ssm.controller;

import com.itheima.ssm.domain.Permission;
import com.itheima.ssm.domain.Role;
import com.itheima.ssm.service.IRoleService;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

//角色管理
@Controller
@RequestMapping(path = "/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;

    //    查询所有角色
    @RequestMapping(value = "/findAll")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Role> roles = iRoleService.findAll();
        mv.addObject("roleList", roles);
        mv.setViewName("role-list");
        return mv;
    }

    //    添加角色
    @RequestMapping(path = "/save")
    public String save(Role role) throws Exception {
        iRoleService.save(role);
        return "redirect:findAll";
    }

    //    角色详情
    @RequestMapping(path = "/findById")
    public ModelAndView findById(@RequestParam(name = "id", required = true) String roleId) throws Exception {
        ModelAndView mv = new ModelAndView();
        Role role = iRoleService.findById(roleId);
        mv.addObject("role", role);
        mv.setViewName("role-show");
        return mv;
    }

    //    删除角色
    @RequestMapping(path = "/delById")
    public String delById(@RequestParam(name = "id", required = true) String roleId) throws Exception {
        ModelAndView mv = new ModelAndView();
        iRoleService.delRoleById(roleId);
        return "redirect:findAll";
    }

    //根据角色ID，给角色分配资源权限[先查询]
    @RequestMapping(path = "/findRoleByIdAndAllPermission")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id", required = true) String roleId)
            throws Exception {
        ModelAndView mv = new ModelAndView();
//        1、根据roleId查询出角色
        Role role = iRoleService.findById(roleId);
//        2、根据roleId查询出该角色没有的权限
        List<Permission> permissions = iRoleService.findRoleByIdAndAllPermission(roleId);
        mv.addObject("role", role);
        mv.addObject("permissions", permissions);
        mv.setViewName("role-permission-add");
        return mv;
    }

    //根据角色ID，给角色分配资源权限[添加]
    @RequestMapping(path = "/addPermissionToRole")
    public String addPermissionToRole(@RequestParam(name = "roleId", required = true) String roleId,
                                      @RequestParam(name = "ids", required = true) String[] permissions)
            throws Exception {
        iRoleService.addPermissionToRole(roleId, permissions);
        return "redirect:findAll";
    }
}
